<?php


namespace app\admin\service;


use app\admin\model\AdminAuthGroup;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Paginator;

class AdminGroupService
{


    /**
     * 角色列表
     *
     * @param $extendQueryHelper
     * @param $data
     *
     * @return AdminAuthGroup[]|array|\think\Collection|Paginator
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getList($extendQueryHelper, $data)
    {
        $query = AdminAuthGroup::build()
                      ->where($extendQueryHelper->where)
                      ->order($extendQueryHelper->sort, $extendQueryHelper->order)
                      ->like('title')
                      ->where('status', 1);
        return $extendQueryHelper->is_page ? $query->_paginate() : $query->select();
    }


    /**
     * 角色详情
     *
     * @param int $group_id
     *
     * @return AdminAuthGroup
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    static public function getAdminGroupItem(int $group_id) : AdminAuthGroup
    {
        return AdminAuthGroup::build()
                             ->where('group_id', $group_id)
                             ->findOrFail();
    }

    /**
     * 删除角色
     *
     * @param $group_id
     *
     * @return AdminAuthGroup
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    static public function delAdminGroupItem($group_id)
    {
        $group = AdminAuthGroup::build()->find($group_id);
        if($group->group_type ==1){
            error_abort('系统级角色不允许删除');
        }
        return AdminAuthGroup::build()
                             ->where('group_id', $group_id)
                             ->update(['status' => 0]);
    }

    /**
     * 修改角色
     *
     * @param $request
     *
     * @return AdminAuthGroup
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    static public function setAdminGroupItem($request) : AdminAuthGroup
    {
        $adminAuthGroup = AdminAuthGroup::build()
                                        ->findOrFail($request['group_id']);
        unset($request['group_id']);
        $adminAuthGroup->save($request);
        return $adminAuthGroup;
    }

    /**
     * 添加角色
     *
     * @param $request
     *
     * @return AdminAuthGroup
     */
    public static function addAdminGroupItem($request) : AdminAuthGroup
    {
        $model = new AdminAuthGroup();
        $request['api_rules'] = implode(',', $request['api_rules']);
        $model->save($request);
        return $model;
    }
}